﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SockectServer
{
    public partial class ServerSocket : Form
    {
        public ServerSocket()
        {
            InitializeComponent();
        }
        //启动服务器
        private void bt_start_Click(object sender, EventArgs e)
        {
            try
            {
                //第一步创建一个开始监听的Socket
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //第二步创建Ip地址和端口号对象
                IPAddress ip = IPAddress.Any;
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txt_Point.Text));
                //第三步让监听的Socket绑定Ip地址跟端口号
                socketWatch.Bind(point);
                //设置监听队列
                socketWatch.Listen(int.Parse(this.tb_num.Text));

                Thread t = new Thread(Listen);
                t.IsBackground = true;
                t.Start(socketWatch);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //循环监听连接的客户端
        Socket socketSend;
        void Listen(object o)
        {
            Socket socketWatch = o as Socket;
            while (true)
            {
                //负责监听的Socket来接收客户端的连接，创建跟客户通讯的Socket
                socketSend = socketWatch.Accept();
                //将远程的连接客服端存储字典集合
                SocketHelper.Intanter.dicScoket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                //添加地址到下拉框与list集合中去
                AddCbItem(socketSend.RemoteEndPoint.ToString());
                AddContent(socketSend.RemoteEndPoint.ToString() + "连接成功");
                Thread t = new Thread(Recive);
                t.IsBackground = true;
                t.Start(socketSend);
            }
        }

        //循环接收发送过来的数据
        void Recive(object o)
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                try
                {
                    string str = "";
                    //客户端连接成功后，服务器接收客服端发送过来的数据
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    //实际接收的有效字节
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    if (buffer[0] == 0)
                    {
                        str = socketSend.RemoteEndPoint.ToString() + ":\r\n" + "   " + Encoding.UTF8.GetString(SocketHelper.Intanter.RemoveFbyte(buffer), 0, r);

                    }
                    else if (buffer[0] == 1)
                    {
                        str = socketSend.RemoteEndPoint.ToString() + ":\r\n" + "   " + SocketHelper.Intanter.ShowImgByByte(SocketHelper.Intanter.RemoveFbyte(buffer));

                        SocketHelper.Intanter.SendMessage(buffer);
                    }
                    byte[] newbuffer = SocketHelper.Intanter.SendMessageToClient(str);
                    SocketHelper.Intanter.SendMessage(newbuffer);
                    AddContent(socketSend.RemoteEndPoint.ToString() + ":" + str);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

            }
        }

        //将连接的IP添加到下拉框
        public void AddCbItem(string ItemName)
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                cb_IP.Items.Add(ItemName);
                SocketHelper.Intanter.IPItem.Add(ItemName);
            }));
        }

        //将接受到的内容显示出来
        private void AddContent(string content)
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                rtb_log.AppendText(content + " ");
                rtb_log.AppendText("\r\n");
                rtb_log.Focus();//先获取焦点
                rtb_log.Select(rtb_log.TextLength, 0);//选中数据末尾0个字符
                rtb_log.ScrollToCaret();//将滚动条移动到当前位置
                                        //记录收到的字符个数
                                        //toolStripStatusLabel1.Text += (int.Parse(toolStripStatusLabel1.Text) + content.Length).ToString();
            }));
        }

        //弹出客户端
        private void bt_Open_Click(object sender, EventArgs e)
        {
            //new ClientSocket().Show();
        }

        //选择连接的客户端发送数据
        private void bt_send_Click(object sender, EventArgs e)
        {
            string msg = this.rtb_log.Text.Trim();

            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(msg);
                //获得用户在下拉框的IP地址
                string ip = this.cb_IP.Text;
                SocketHelper.Intanter.dicScoket[ip].Send(buffer);
                socketSend.Send(buffer);
            }
            catch (Exception ex)
            {
                
            }

            //socketSend.Send(SocketHelper.Intanter.SendMessageToClient(msg, SocketHelper.MessageType.news));
        }
    }

}
